package com.mspbots.core.tsheets;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mspbots.core.AbstractBaseServiceImpl;
import com.mspbots.core.wise.controller.params.UserMappingParams;
import com.mspbots.core.wise.model.dto.UserMappingResponse;
import com.mspbots.core.wise.service.TenantUserMappingService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * com.mspbots.core.service.impl.SheetsTimeServiceImpl
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/26
 */
@Service
@RequiredArgsConstructor
public class SheetsTimeServiceImpl extends AbstractBaseServiceImpl<SheetsTimeMapper, SheetsTime>
        implements SheetsTimeService {

    private final TenantUserMappingService userMappingService;
    private final SheetsUserMapper sheetsUserMapper;

    @Override
    public IPage<SheetsTime> analysisPage(Page<SheetsTime> page, SheetsTime queryParams) {
        QueryWrapper<SheetsTime> queryWrapper = new QueryWrapper<>(queryParams);
        if (queryParams.getStartTimeFrom() != null) {
            queryWrapper.ge("start_time", queryParams.getStartTimeFrom());
        }
        if (queryParams.getStartTimeTo() != null) {
            queryWrapper.le("start_time", queryParams.getStartTimeTo());
        }
        if (queryParams.getTsUid() != null) {
            UserMappingResponse mappingResponse = this.userMappingService.findByOne(UserMappingParams.builder()
                    .tenantId(queryParams.getTenantId()).tenantUserId(queryParams.getTsUid()).build());
            if (mappingResponse != null) {
                queryWrapper.le("sheet_user_id", queryParams.getSheetUserId());
            } else {
                queryWrapper.le("sheet_user_id", 0);
            }

        }

        page.addOrder(OrderItem.desc("id"));
        IPage<SheetsTime> sheetsTimePage = baseMapper.selectPage(page, queryWrapper);
        IPage<SheetsTime> sheetTimesDtoPage = new Page<>(sheetsTimePage.getCurrent(),
                sheetsTimePage.getSize(), sheetsTimePage.getTotal());
        return sheetTimesDtoPage.setRecords(this.covertToDto(sheetsTimePage.getRecords()));

    }

    @Override
    public SheetsTime findLast(SheetsTime queryParams) {
        QueryWrapper<SheetsTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", queryParams.getTenantId());
        queryWrapper.eq("sheet_user_id", queryParams.getSheetUserId());
        queryWrapper.between("start_time",
                queryParams.getStartTimeFrom(),
                queryParams.getStartTimeTo());
        queryWrapper.orderByAsc("start_time");
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }


    @Override
    public List<SheetsTime> analysisList(SheetsTime queryParams) {
        QueryWrapper<SheetsTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", queryParams.getTenantId());
        queryWrapper.between("last_modified",
                LocalDateTime.of(queryParams.getLastModified().toLocalDate(), LocalTime.MIN),
                LocalDateTime.of(queryParams.getLastModified().toLocalDate(), LocalTime.MAX));
        queryWrapper.orderByAsc("start_time");
        List<SheetsTime> list = baseMapper.selectList(queryWrapper);
        return this.covertToDto(list).stream()
                .filter(item -> !ObjectUtils.isEmpty(item.getTsUid()))
                .collect(Collectors.toList());

    }

    private List<SheetsTime> covertToDto(List<SheetsTime> sheetsTimeStream) {
        return sheetsTimeStream.parallelStream().peek(sheetsTime -> {
            QueryWrapper<SheetsUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("tenant_id", sheetsTime.getTenantId());
            userQueryWrapper.eq("sheet_user_id", sheetsTime.getSheetUserId());
            SheetsUser sheetsUser = sheetsUserMapper.selectOne(userQueryWrapper);
            if (sheetsUser != null) {
                sheetsTime.setSheetUserName(sheetsUser.getFirstName() + " " + sheetsUser.getLastName());
                sheetsTime.setTsUid(sheetsUser.getId());
            }
        }).collect(Collectors.toList());
    }
}
